package cn.zyp.stusystem.service.impl;

import cn.zyp.stusystem.entity.GradeClass;
import cn.zyp.stusystem.entity.Student;
import cn.zyp.stusystem.mapper.ClassMapper;
import cn.zyp.stusystem.mapper.StudentMapper;
import cn.zyp.stusystem.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private ClassMapper classMapper;

    @Override
    public IPage<Student> selectPageStudent(Integer page, Integer size, Integer grade, Long classId, String name) {

        //创建分页对象
        IPage<Student> studentPage = new Page<>(page,size);

        //构建查询条件
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(grade != null, "grade", grade);
        queryWrapper.eq(classId != null && classId > 0, "class_id", classId);
        queryWrapper.like(name != null && !name.isEmpty(), "name", name);
        studentPage = baseMapper.selectPage(studentPage, queryWrapper);

        //关联查询班级名称
        List<Student> students = studentPage.getRecords();
        if (students != null && students.size() > 0) {
            List<Long> classIds = students.stream().map(Student::getClassId).collect(Collectors.toList());
            QueryWrapper<GradeClass> classQueryWrapper = new QueryWrapper<>();
            classQueryWrapper.in("id", classIds);
            List<GradeClass> classes = classMapper.selectList(classQueryWrapper);

            //转换为Map
            Map<Long, String> classMap = classes.stream().collect(Collectors.toMap(GradeClass::getId, GradeClass::getName));

            students.forEach(student -> student.setClassName(classMap.get(student.getClassId())));


        }
        return studentPage;
    }
}

